package com.xiaoluo.service;

import com.xiaoluo.cd.dao.ProjServersMapper;
import com.xiaoluo.cd.dao.ProjectsMapper;
import com.xiaoluo.cd.entity.base.*;
import com.xiaoluo.common.enums.ServerTypeEnum;
import com.xiaoluo.web.form.GitCommit;
import com.xiaoluo.web.form.GitProject;
import com.xiaoluo.web.form.GitRepository;
import com.xiaoluo.web.form.ProjectForm;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Project : XL-CD
 * Package : com.xiaoluo.service
 * Created by Willian.
 * Date  : 2015/12/28 11:43.
 */
@Service
@Transactional
public class ProjectService {
    private final static Logger logger = LoggerFactory.getLogger(ProjectService.class);

    @Autowired
    ProjectsMapper projectsMapper;
    @Autowired
    ProjServersMapper projServersMapper;
    @Autowired
    ServerService  serverService;

    public List<Projects> list(){
        ProjectsExample examle = new ProjectsExample();
        examle.setOrderByClause("proj_name desc");

        return projectsMapper.selectByExample(examle);
    }


    /**
     * 根据ID查询项目详情
      * @param id
     * @return
     */
    public ProjectForm findById(Long id){
        ProjectForm result = new ProjectForm();

        Projects proj = projectsMapper.selectByPrimaryKey(id);
        BeanUtils.copyProperties(proj,result);
        List<Servers> buildServers = serverService.queryByType(0);
        List<Servers> testServers = serverService.queryByType(1);
        List<Servers> productServers = serverService.queryByType(2);
        List<Servers> quickServers = serverService.queryByType(3);
        result.setProductServers(productServers);
        result.setTestServers(testServers);
        result.setBuildServers(buildServers);
        result.setQuickServers(quickServers);

        return  result;
    }


    /**
     *
     * @param projects
     */
    public void save(Projects projects,String testServers,String productServers){
        if(projects != null){
            if(projects.getId() != null){
                Projects temp = projectsMapper.selectByPrimaryKey(projects.getId());
                projects.setLastCommitDate(temp.getLastCommitDate());
                projects.setUpdateAt(new Date());
                projectsMapper.updateByPrimaryKey(projects);
            }else {
                projectsMapper.insert(projects);
            }
            cleanProjServers(projects);
            saveProjServers(projects,testServers,productServers);
        }
    }
    private void cleanProjServers(Projects proj){
        Projects project = getByGit(proj.getGitSshUrl());
        if(project != null){
            ProjServersExample example = new ProjServersExample();
            example.createCriteria().andProjIdEqualTo(project.getId());
            projServersMapper.deleteByExample(example);
        }
    }
    private void saveProjServers(Projects proj,String testServers,String productServers){


        Projects project = getByGit(proj.getGitSshUrl());
        if(project != null){
            if(testServers != null && !"".equals(testServers)){
                String[] items = testServers.split(",");
                if(items != null && items.length >0){
                    for (String item:items){
                        if(!"".equals(item.trim())){
                            ProjServers ps = new ProjServers();
                            ps.setProjId(project.getId());
                            ps.setServerId(Long.parseLong(item));
                            projServersMapper.insert(ps);
                        }
                    }
                }
            }
            if(productServers != null && !"".equals(productServers)){
                String[] items = productServers.split(",");
                if(items != null && items.length >0){
                    for (String item:items){
                        if(!"".equals(item.trim())){
                            ProjServers ps = new ProjServers();
                            ps.setProjId(project.getId());
                            ps.setServerId(Long.parseLong(item));
                            projServersMapper.insert(ps);
                        }
                    }
                }
            }
        }
    }

    /**
     *
     * @param id
     * @return
     */
    public Projects get(Long id){
        return projectsMapper.selectByPrimaryKey(id);
    }

    /**
     *
     * @param gitUrl
     * @return
     */
    public Projects getByGit(String gitUrl){
        logger.info("getByGit :{}",gitUrl);

        ProjectsExample example = new ProjectsExample();
        example.createCriteria().andGitSshUrlEqualTo(gitUrl);

        List<Projects> list = projectsMapper.selectByExample(example);
        if(list != null && list.size() >0){
            return list.get(0);
        }

        return  null;
    }

    /**
     * 更新projects
     * @param project
     */
    public void saveGitProject(GitProject project){
        if(project != null && project.getObject_kind() != null && "push".equals( project.getObject_kind())){
            GitRepository repository = project.getRepository();
            //
            Projects projects = getByGit(repository.getGit_ssh_url());

            if(projects == null){
                projects = new Projects();
                projects.setCreateAt(new Date());
                projects.setGitSshUrl(repository.getGit_ssh_url());
            }

            projects.setTotalCommitsCount(project.getTotal_commits_count());
            projects.setProjDesc(repository.getDescription());
            projects.setHomePage(repository.getHomepage());
            projects.setProjName(repository.getName());
            StringBuffer buffer = new StringBuffer();
            for(GitCommit commit : project.getCommits()){
                try {
                    Date date = DateUtils.parseDate(commit.getTimestamp(), "yyyy-MM-dd'T'hh:mm:ss+08:00");
                    projects.setLastCommitDate(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                buffer.append(commit.getMessage()).append("\n\r");
            }
            projects.setChangeLog(buffer.toString());
            //save2db
            if(projects.getId() != null){
                projectsMapper.updateByPrimaryKey(projects);
            }else {
                projects.setAutoBuild((byte)0);
                projectsMapper.insert(projects);
            }

        }
    }

    /**
     * 1、构建项目目录
     * 2、下载项目代码
     * 3、获取项目分支
     *
     *
     */
    public  void init(){
        //1、构建项目目录

        //2、下载项目代码

        //3、获取项目分支
    }

    /**
     * 同步项目代码
     * 更新项目分支
     */
    public void sync(){
        //同步项目代码

        //更新项目分支
    }
}
